package com.zhengaz.common.log.aspect;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.zhengaz.common.core.entity.R;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhengzg
 * @create 2023-05-31 9:25
 */
@Slf4j
@Component
@Aspect
public class ControllerLogAspect {

	@Pointcut("execution(* com.zhengaz..controller..*.*(..))")
	private void cut() {}

	@Around("cut()")
	@SneakyThrows
	public Object around(ProceedingJoinPoint point) {
		// 获取类名
		String strClassName  = point.getTarget().getClass().getName();
		// 获取方法名
		String strMethodName = point.getSignature().getName();
		// 获取参数
		Object[] args = point.getArgs();
		// 判断请求参数类型
		if (ArrayUtil.isNotEmpty(args)) {
			List<Object> result = Arrays.stream(args)
					.filter(arg -> (!(arg instanceof HttpServletRequest)
							&& !(arg instanceof HttpServletResponse)
							&& !(arg instanceof MultipartFile)))
					.collect(Collectors.toList());
			log.info("{}.{} 入参：{}",strClassName,strMethodName, JSONUtil.parse(result));
		}
		// 判断返回结果
		Object proceed = point.proceed();
		if (Objects.nonNull(proceed) && proceed instanceof R) {
			log.info("{}.{} 返回结果：{}",strClassName,strMethodName,JSONUtil.parse(proceed));
		}
		return proceed;
	}
}
